package com.knowledge.knowledge_notes.service.impl;

import com.knowledge.knowledge_notes.dao.UserDao;
import com.knowledge.knowledge_notes.dto.UserDTO;
import com.knowledge.knowledge_notes.pojo.AdminRole;
import com.knowledge.knowledge_notes.pojo.LoginUser;
import com.knowledge.knowledge_notes.service.AdminRoleService;
import com.knowledge.knowledge_notes.service.AdminUserRoleService;
import com.knowledge.knowledge_notes.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDAO;
    @Autowired
    AdminRoleService adminRoleService;
    @Autowired
    AdminUserRoleService adminUserRoleService;

    public List<UserDTO> list() {
        List<LoginUser> users = userDAO.findAll();
        // Find all roles in DB to enable JPA persistence context.
//        List<AdminRole> allRoles = adminRoleService.findAll();
        List<UserDTO> userDTOS = users
                .stream().map(user -> (UserDTO) new UserDTO().convertFrom(user)).collect(Collectors.toList());
        userDTOS.forEach(u -> {
            List<AdminRole> roles = adminRoleService.listRolesByUser(u.getUserName());
            u.setRoles(roles);
        });
        return userDTOS;
    }

    @Override
    public void editUser(LoginUser user) {
        LoginUser userInDB = userDAO.findByUserName(user.getUserName());
        userInDB.setName(user.getName());
        userInDB.setPhone(user.getPhone());
        userInDB.setEmail(user.getEmail());
        userDAO.save(userInDB);
        adminUserRoleService.saveRoleChanges(userInDB.getId(), user.getRoles());
    }

    @Override
    public boolean isExist(String userName) {
        LoginUser user = findByUserName(userName);
        return null != user;
    }

    @Override
    public LoginUser findByUserName(String userName) {
        return userDAO.findByUserName(userName);
    }

    @Override
    public LoginUser get(String userName, String password) {
        return userDAO.getByUserNameAndPassword(userName, password);
    }

    @Override
    public void add(LoginUser user) {
        userDAO.save(user);
    }
}
